#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import wsgiref.handlers
import logging, cgi, os
from google.appengine.api import mail
from google.appengine.ext import webapp

""" Class that sends mails :)
"""
class Sendmail(webapp.RequestHandler):

  def post(self):
      
    """Dictionary of authorized fields
    Add these fields in your form (i.e <input type="text" name="sender">,...)
    You can hardcode some fields, by default all mandatory fields must be set in the form 
    """                         
    fields = {'sender':'',
              'to':'','cc':'','bcc':'',
              'reply_to':'',
              'subject':'',
              'body':'','html':'',
              'attachments':'',
              'redirect_url':''}
    
    """List of authorized referers
    (i.e : ['http://localhost:8080/testform.html',...])
    Add your own web form url to prevent spamming.
    If auth_referers = [], your current form is open to the world :)
    
    To check your "referer" un-comment this line and search for 'Referer'
    logging.info('Headers = %s', self.request.headers)
    """ 
    auth_referers = []  
    
    if auth_referers:
        referer = self.request.referer
        if referer not in auth_referers:
            return 
    
    email = mail.EmailMessage()
    
    #logging.info('Headers = %s', self.request.headers)
    #logging.info('Post = %s', self.request.POST)
    
    for f,v in fields.iteritems():
        if v:
            if f !='redirect_url':
                v = unicode_to_string(v)
                setattr(email, f, v)
            continue
        
        if f == 'attachments':
            attachments = self.request.POST.getall('attachments')
            val = get_attachments(attachments)
        else :
            val = self.request.get(f,default_value = '')
            
        if val:
            val = unicode_to_string(val)
            fields[f] = val
            if f !='redirect_url':
                setattr(email, f, val)
        
    #logging.info('fields_value = %s', fields)
    
    try:
        email.check_initialized()
        email.send()
    except Exception, e:
        #logging.exception('Sendmail')
        pass
    finally:
        if 'redirect_url' in fields:
            self.redirect(fields['redirect_url'])
  get = post
  
def get_attachments(attachments):
    files = []
    for att in attachments:
        if isinstance(att, cgi.FieldStorage):
            name, ext = os.path.splitext(att.filename)
            files.append((unicode_to_string(name + ext.lower()), att.value))
    return files

def unicode_to_string(s):
    if isinstance(s, unicode):
        s = s.encode('utf-8')
    return s

def main():
  application = webapp.WSGIApplication([('/sendmail', Sendmail)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
